package com.zhike.service.file;

import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zhike.common.conf.IMBaseConf;
import com.zhike.common.constant.Constants;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class AttachmentUploader extends UploaderRoot {
	@Autowired
	private IMBaseConf baseConf;

	@Override
	public String getFileSaveDir() {
		return baseConf.getDIR_USER_UPLOAD();
	}

	@Override
	public void onUploadSucess(HashMap<String, Object> parametersFromClient) throws Exception {
		// 因为服务端是支持多文件上传的API，所以客户端单独把文件名带过来了，方便使用！
		String fileName = (String) parametersFromClient.get("file_name");

		log.debug("[" + getDebugTAG() + "] " + fileName + "数据上传成功，马上处理其它业务逻辑...");

		// 客户端传过来的数据（参数）的合法性检查
		// if (fileName != null) {
		// String uploadPath = getFileSaveDir();
		// // 文件已经保存到的磁盘绝对路径
		// File filePath = new File(uploadPath + File.separator + fileName);

		// if (filePath.exists()) {
		// // 生成原图的缩略图并存到磁盘
		// File thumbnailFilePath = new File(uploadPath + File.separator + "th_" +
		// fileName);
		// // 如果该md5文件名命名（其实此md5码就是文件数据的指纹）存在，即意味着不需要写入磁盘了
		// if (!thumbnailFilePath.exists()) {
		// // 20170306后的缩略图生成算法
		// ImgEqualScaleAndCutHelper.saveImageAsJpg(filePath.getAbsolutePath(),
		// thumbnailFilePath.getAbsolutePath(), 450, 450);// 20190605
		// // ：为了更好的适应高dpi手机，已由原200*200改为450*450
		// }
		// } else {
		// log.error("[" + getDebugTAG() + "] "
		// + fileName + "为何不存在？(绝对路径=" + filePath.getAbsolutePath() + ")");
		// }
		// } else {
		// throw new Exception("[" + getDebugTAG() + "] 无效的参数：" + "fileName=" + fileName
		// + ".");
		// }
	}

	@Override
	public void onUploadFailure(Exception ex) {
		log.error("[" + getDebugTAG() + "] 处理图片消息上传时出错了，" + ex.getMessage(), ex);
	}

	@Override
	public String getDebugTAG() {
		return "HTTP图片消息";
	}

	@Override
	public String getPathTag() {
		return Constants.UPLOAD_CHAT + "/attachment";
	}

	/**
	 * txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar,png
	 */
	@Override
	public Set<String> getDetectedTypes() {
		Set<String> allowExtensions = new HashSet<>();
		allowExtensions.add("text/plain");// txt
		allowExtensions.add("application/pdf"); // pdf
		allowExtensions.add("application/octet-stream");
		allowExtensions.add("application/msword");// word
		allowExtensions.add("application/vnd.ms-excel");// excel
		allowExtensions.add("application/x-tika-msoffice");// ppt
		allowExtensions.add("application/zip"); // zip/rar
		allowExtensions.add("image/png");
		allowExtensions.add("image/jpeg");
		allowExtensions.add("image/jpg");
		allowExtensions.add("image/gif");
		allowExtensions.add("video/quicktime");// mp4
		return allowExtensions;
	}
}
